<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="公告标题" prop="title">
        <el-input
          v-input-restrict
          v-model="queryParams.title"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-input-restrict
          v-model="queryParams.creator"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布日期" prop="date">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="queryParams.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="$pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
    <div class="commonMenu">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="">全部</el-menu-item>
        <el-menu-item index="0">待发送</el-menu-item>
        <el-menu-item index="1">已发送</el-menu-item>
      </el-menu>
    </div>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="公告编号" align="center" prop="noticeId" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
          <el-tag type="warning" v-if="scope.row.noticeStatus == 0"
            >待发送</el-tag
          >
          <el-tag
            type="success"
            v-if="scope.row.noticeStatus == 1 || scope.row.noticeStatus == 2"
            >已发送</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="公告标题" align="center" prop="noticeTitle" />

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="公告内容" align="center" prop="noticeContent">
        <template slot-scope="scope">
          <span v-html="scope.row.noticeContent"></span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--  noticeStatus    公告状态 0:待发送 1.已发送 2.已下架 -->
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            v-if="scope.row.noticeStatus == 1 || scope.row.noticeStatus == 2"
            @click="handleUpdate(scope.row, 'view')"
            >详情</el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-bottom"
            v-if="scope.row.noticeStatus == 1"
            @click="handleTakedown(scope.row)"
            >下架</el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.noticeStatus == 0"
            @click="handleUpdate(scope.row, 'update')"
            >编辑</el-button
          >
          <el-button
            v-preventReClick
            v-if="scope.row.noticeStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        @submit.native.prevent
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <div v-if="title === '查看公告'">
                {{ form.noticeTitle }}
              </div>
              <el-input
          v-input-restrict
                v-else
                v-model="form.noticeTitle"
                placeholder="请输入公告标题"
                maxlength="40"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="startTime">
              <el-checkbox
                v-model="timePickerUse"
                :disabled="title === '查看公告'"
                >定时发送</el-checkbox
              >
              <el-date-picker
                :picker-options="pickerOptionsEnd"
                :disabled="!timePickerUse || title === '查看公告'"
                style="margin-left: 15px"
                v-model="form.startTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="收件人" prop="receiverList">
          <!-- 端口 -->
          <el-table :data="ports">
            <el-table-column label="端口" align="center" width="200">
              <template slot-scope="scope">
                <span
                  ><el-checkbox
                    :disabled="title === '查看公告'"
                    v-model="scope.row.checked"
                    :indeterminate="scope.row.isIndeterminate"
                    @change="
                      handleCheckAllChange($event, 'ports', scope.$index)
                    "
                    >{{ scope.row.keyName }}</el-checkbox
                  ></span
                >
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center">
              <template slot-scope="scope">
                <el-checkbox
                  :disabled="title === '查看公告'"
                  @change="
                    handleCheckedRoleChange(
                      $event,
                      'ports',
                      scope.$index,
                      index
                    )
                  "
                  v-for="(item, index) in scope.row.List"
                  v-model="item.checked"
                  :key="index"
                  >{{ item.keyName }}</el-checkbox
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色 -->
          <el-table :data="roles">
            <el-table-column label="角色" align="center" width="200">
              <template slot-scope="scope">
                <span
                  ><el-checkbox
                    :disabled="title === '查看公告'"
                    v-model="scope.row.checked"
                    :indeterminate="scope.row.isIndeterminate"
                    @change="
                      handleCheckAllChange($event, 'roles', scope.$index)
                    "
                    >{{ scope.row.keyName }}</el-checkbox
                  ></span
                >
              </template>
            </el-table-column>
            <el-table-column label="分院" align="center">
              <template slot-scope="scope">
                <el-checkbox
                  :disabled="title === '查看公告'"
                  @change="
                    handleCheckedRoleChange(
                      $event,
                      'roles',
                      scope.$index,
                      index
                    )
                  "
                  v-for="(item, index) in scope.row.List"
                  v-model="item.checked"
                  :key="index"
                  >{{ item.keyName }}</el-checkbox
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="公告内容" prop="noticeContent">
          <div v-if="title === '查看公告'" v-html="form.noticeContent"></div>
          <wangEditor v-else v-model="form.noticeContent"></wangEditor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="cancel"
          v-if="title == '添加公告' || title == '编辑公告'"
          >取 消</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('save')"
          v-if="title == '添加公告' || title == '编辑公告'"
          >保 存</el-button
        >
        <el-button @click="cancel" type="primary" v-if="title == '查看公告'"
          >关 闭</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('add')"
          v-if="title == '添加公告' || title == '编辑公告'"
          >发 送</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//TODO 只写了全局模板
import wangEditor from "@/components/wangEditor.vue";
import {
  addPost_notice,
  getPost_notice,
  listPost_notice,
  updatePost_notice,
  delPost_notice,
  changePublishStatus,
} from "@/api/notificationCenter/notification";
import { listRole } from "@/api/system/role";
import { listPost_branch } from "@/api/schoolOrganization/organization";
export default {
  components: { wangEditor },
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      pickerOptionsEnd: {
        disabledDate: (time) => {
          // 获取当前日期和时间
          const currentDate = new Date();
          currentDate.setDate(currentDate.getDate() - 1);
          const currentTime = currentDate.getTime();

          // 获取选择的日期和时间
          const selectedTime = time.getTime();

          // 比较日期和时间
          if (selectedTime < currentTime) {
            return true; // 禁用选择的日期
          }

          return false; // 允许选择的日期和时间
        },
      },
      timePickerUse: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // level
      level: [],
      // 查询参数
      activeIndex: "",
      queryParams: {
        date: "",
        pageNum: 1,
        pageSize: 10,
        creator: undefined,
        title: undefined,
        noticeType: 2,
        publishStatus: undefined,
      },
      levels: [
        { id: 1, name: "级别一" },
        { id: 2, name: "级别二" },
      ],
      // 表单参数
      form: {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeContent: undefined,
        noticeType: 2,
        startTime: "",
        endTime: "",
        receiverList: undefined,
        publishStatus: true,
        readStatus: false,
        remark: "",
        status: "",
      },
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" },
        ],
        noticeContent: [
          { required: true, message: "公告内容不能为空", trigger: "blur" },
        ],
        receiverList: [
          { required: true, message: "收件人不能为空", trigger: "blur" },
        ],
      },
      roles: [
        {
          roleId: 3,
          keyName: "教师",
          checked: false,
          isIndeterminate: false,
          status: 0,
          type: 5,
          List: [],
        },
        {
          roleId: 4,
          keyName: "学生",
          checked: false,
          isIndeterminate: false,
          status: 0,
          type: 5,
          List: [],
        },
      ],
      ports: [
        {
          keyName: "教务端",
          checked: false,
          isIndeterminate: false,
          List: [],
          type: 1,
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getBranch();
    this.getRoleList();
  },
  methods: {
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((response) => {
        this.roles.map((role) => {
          role.List = response.rows.map((item) => {
            return {
              branchId: item.branchId,
              keyName: item.branchName,
              type: 2,
              status: "0",
            };
          });
        });
      });
    },
    getRoleList() {
      listRole().then((res) => {
        this.ports.map((port) => {
          port.List = [];
          res.rows.map((role) => {
            if (role.type == 1) {
              role.checked = false;
              port.List.push({
                keyName: role.roleName,
                roleId: role.roleId,
                status: role.status,
                type: 5,
              });
            }
          });
        });
      });
    },
    // el-menu
    handleSelect(key, keyPath) {
      //   noticeStatus    公告状态 0:待发送 1.已发送 2.已下架
      if (key == "") {
        this.queryParams.status = "";
      } else if (key == 0) {
        this.queryParams.status = 0;
      } else {
        this.queryParams.status = 3;
      }

      this.getList();
    },
    /* 分院-全选 */
    /* 角色-全选 */
    handleCheckAllChange(val, datakey, portIndex) {
      this[datakey][portIndex].List.map((item) => {
        item.checked = val;
      });
      this[datakey][portIndex].isIndeterminate = false;
    },
    handleCheckedRoleChange(value, datakey, portIndex, roleIndex) {
      this.$set(
        this[datakey][portIndex].List,
        roleIndex,
        this[datakey][portIndex].List[roleIndex]
      );
      this.$forceUpdate();
      let checkedCount = 0;
      this[datakey][portIndex].List.map((item) => {
        if (item.checked) {
          checkedCount++;
        }
      });
      this[datakey][portIndex].checked =
        checkedCount === this[datakey][portIndex].List.length;
      this[datakey][portIndex].isIndeterminate =
        checkedCount > 0 && checkedCount < this[datakey][portIndex].List.length;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams);
      let params = { ...this.queryParams };
      params.startTime = params.date[0];
      params.endTime = params.date[1];
      delete params.date;
      console.log(params);
      listPost_notice(params).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeContent: undefined,
        startTime: "",
        endTime: "",
        noticeType: 2,
        receiverList: undefined,
        publishStatus: true,
        readStatus: false,
        remark: "",
        status: "",
        noticeStatus: "",
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.schoolId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 用于清空时间 以及 清空勾选
      this.timePickerUse = false;
      this.ports.map((port) => {
        port.checked = false;
        port.isIndeterminate = false;
        port.List.map((role) => {
          role.checked = false;
        });
      });
      this.roles.map((role) => {
        role.checked = false;
        role.isIndeterminate = false;
        role.List.map((branch) => {
          branch.checked = false;
        });
      });
      this.open = true;
      this.title = "添加公告";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      const noticeId = row.noticeId || this.ids;
      getPost_notice(noticeId).then((response) => {
        this.form = response.data;
        this.open = true;
        if (this.form.startTime) {
          this.timePickerUse = true;
        }
        // 初始化端口勾选
        this.ports.map((port) => {
          let checkedCount = 0;
          port.List.map((role) => {
            role.checked = false;
            this.form.receiverList.map((item) => {
              if (item.roleId == role.roleId) {
                role.checked = true;
                checkedCount++;
              }
            });
          });
          port.checked = checkedCount === port.List.length;
          port.isIndeterminate =
            checkedCount > 0 && checkedCount < port.List.length;
        });
        // 初始化角色勾选
        // 遍历角色
        this.roles.map((role) => {
          let checkedCount = 0;
          // 遍历分院
          role.List.map((branch) => {
            branch.checked = false;
            // 遍历接口返回的接收者列表
            this.form.receiverList.map((item) => {
              if (item.roleId == role.roleId) {
                if (
                  item.branchIds.split(",").indexOf(branch.branchId + "") !== -1
                ) {
                  branch.checked = true;
                  checkedCount++;
                }
              }
            });
          });
          role.checked = checkedCount === role.List.length;
          role.isIndeterminate =
            checkedCount > 0 && checkedCount < role.List.length;
        });
        this.title = type == "view" ? "查看公告" : "编辑公告";
      });
    },
    /** 提交按钮 */
    submitForm: function (type) {
      let arr = [];
      //提交的时候处理端口
      this.ports.map((port) => {
        port.List.map((role) => {
          if (role.checked) {
            arr.push({
              roleId: role.roleId,
              keyName: role.keyName,
              status: role.status,
              type: role.type,
            });
          }
        });
      });
      // 提交的时候处理角色
      this.roles.map((role) => {
        if (role.checked || role.isIndeterminate) {
          let branchIds = [];
          role.List.map((item) => {
            if (item.checked) {
              branchIds.push(item.branchId);
            }
          });
          arr.push({
            roleId: role.roleId,
            keyName: role.keyName,
            status: role.status,
            type: role.type,
            branchIds: branchIds.join(","),
          });
        }
      });
      this.form.receiverList = arr;
      if (
        this.timePickerUse &&
        new Date(this.form.startTime).getTime() < new Date().getTime()
      ) {
        this.$modal.msg("显示时间必须大于当前时间");
        return false;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = { ...this.form };
          data.startTime = this.timePickerUse ? this.form.startTime : null;
          if (this.form.noticeId != undefined) {
            data.noticeStatus = type == "add" ? 1 : 0;
            data.publishStatus = type == "add" ? true : false;
            updatePost_notice(data).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            data.noticeStatus = type == "add" ? 1 : 0;
            data.publishStatus = type == "add" ? true : false;
            addPost_notice(data).then((response) => {
              this.$modal.msgSuccess(type == "add" ? "发送成功" : "保存成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeId = row.noticeId || this.ids;
      this.$modal
        .confirm(`确认删除【${row.noticeTitle}】吗？删除后不可恢复`)
        .then(async () => {
          await delPost_notice(noticeId);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /* 下架操作 */
    handleTakedown(item) {
      this.$modal
        .confirm(`确认下架【${item.noticeTitle}】吗？此操作不可撤销`)
        .then(async () => {
          await changePublishStatus({
            noticeId: item.noticeId,
            publishStatus: false,
          });
          this.getList();
          this.$modal.msgSuccess("下架成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-menu-item:hover {
  border-bottom: 1px solid #e6e6e6 !important;
}

::v-deep .el-menu--horizontal > .el-menu-item.is-active:hover {
  border-bottom: 2px solid #11a983 !important;
}
</style>
